<template>
	<div class="cif-image">
		<div class="cif-image-label">
			{{ data.displayName }}
		</div>
		<div class="cif-image-wrapper">
			<el-upload
				:action="url"
				:headers="{ 'Fusion-Auth': accessToken }"
				:with-credentials="true"
				:data="e9y"
				:show-file-list="false"
				:before-upload="handleBeforeUpload"
				:on-success="handleUploadSuccess"
				:on-error="handleUploadError"
				:accept="acceptList">
				<el-image v-if="imageUrl" :src="imageUrl" class="image">
					<!-- <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div> -->
				</el-image>
				<!-- <img v-if="imageUrl" :src="imageUrl" class="image" /> -->
				<el-icon class="el-icon-plus" v-else><Plus /></el-icon>
			</el-upload>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, ref, inject, watch, computed } from 'vue';
import { findConfigDataByName } from '@CIF/Utils/reduce-config';
import axios from 'axios';
import _ from 'lodash';
import storage from '@/utils/storage';
import { ElMessage } from 'element-plus';
import { getLocalstorage } from '@/utils/localstorage';

const configuration: any = inject('configuration');
const props = defineProps({
	data: {
		type: Object,
		default() {
			return {};
		}
	}, // cpntTreeNode
	arrayName: String,
	childName: String
});

const emit = defineEmits(['handleValueChange']);
const value = ref(props.data.value);
// const config = ref(props.data.config || {});
const e9y = ref({ e9y: '' });
const accessToken = getLocalstorage('access_token');
const imageUrl = ref('');
const url = import.meta.env?.VITE_APP_UPLOAD_API || '/api/sys-storage/upload';

// const conf = computed(() => {
// 	return typeof configuration === 'function' ? configuration() : configuration;
// });
const acceptList = computed(() => {
	return props.data.config.accept || '';
});

watch(
	() => props.data,
	(nv) => {
		// console.log('3333', 'props.data', nv);
		value.value = nv.value;
		if (nv.value) {
			axios({
				method: 'get',
				url: '/sys-storage/download',
				responseType: 'blob',
				params: {
					f8s: nv.value
				}
			}).then((res: any) => {
				imageUrl.value = window.URL.createObjectURL(res.data);
			});
		}
	},
	{ deep: true, immediate: true }
);

function handleBeforeUpload(file: any) {
	// const accept = _.get(this.config, 'accept', '')
	// const isAccept = _.indexOf(accept.split(','), file.name.split('.').pop())
	const isLt2M = file.size / 1024 / 1024 < 2;
	// if (isAccept < 0) {
	//   this.$message.error(`上传图片格式不对!请参考格式设定${accept}`)
	// }
	if (!isLt2M) {
		ElMessage.error('上传图片大小不能超过 2MB!');
	}
	// return isAccept >= 0 && isLt2M
	return isLt2M;
}

function handleUploadSuccess(response: any, file: any) {
	const fileToken = _.get(response, 'data.fileToken');
	handleChange(fileToken);
	imageUrl.value = URL.createObjectURL(file.raw);
	// this.$copyText(fileToken).then(
	// 	(e) => {
	// 		ElMessage('图片fileToken已经被复制到粘贴板');
	// 	},
	// 	(e) => {
	// 		ElMessage.error('图片fileToken复制失败', e);
	// 	}
	// );
}

function handleUploadError(err: any) {
	ElMessage.error('文件上传失败', err);
}

function handleChange(fileToken: any) {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log('CIF.CC.CCT.C.ImageBox:handleChange 值发生变更', fileToken);
	}
	let c = typeof configuration === 'function' ? configuration() : configuration;
	if (props.arrayName) {
		let data = findConfigDataByName(c, props.arrayName);
		data = findConfigDataByName(data.value, props.childName);
		data = findConfigDataByName(data.value, props.data.name);
		data.value = fileToken;
	} else {
		let data = findConfigDataByName(c, props.data.name);
		data.value = fileToken;
	}
	// 触发值变动通知
	emit('handleValueChange');
}

onMounted(() => {});
defineExpose({});
</script>

<style lang="scss" scoped>
.cif-image {
	display: flex;
	margin-bottom: 10px;
	justify-content: space-between;

	&-label {
		display: inline-block;
		overflow: hidden;
		white-space: nowrap;
		text-align: right;
		vertical-align: middle;
		margin-right: 10px;
	}
	&-wrapper {
		.file-card {
			text-align: right;
		}
	}

	.el-icon-plus {
		width: 80px;
		height: 80px;
		line-height: 80px;
		border: 1px dashed #ccc;
	}

	.image {
		width: 80px;
		height: 80px;
	}
}
</style>
